package com.ars.common.service;

import com.ars.common.dao.activity.FileToZip;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/downloadCollegeMaterial")
public class downloadCollegeMaterial extends HttpServlet {

    private static final Logger LOGGER = Logger.getLogger(downloadCollegeMaterial.class.getName());

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        downloadZips(request, response);
    }

    private void downloadZips(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");

        if (id == null || id.isEmpty()) {
            LOGGER.severe("ID is missing in the request.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "ID is required.");
            return;
        }

        LOGGER.info("Received download request for ID: " + id + ", Name: " + name);

        // Original file directory
        String sourceFilePath = getServletContext().getRealPath("/") + "images/" + id;

        // Zip output directory
        String zipFilePath = getServletContext().getRealPath("/") + "images";

        LOGGER.info("Source file path: " + sourceFilePath);

        // File name for the zip
        String fileName = id;

        try {
            // Generate the zip file
            boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
            if (!flag) {
                LOGGER.severe("Failed to create zip file.");
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create zip file.");
                return;
            }

            // Name of the zip file
            String zipFileName = id + ".zip";
            // Full path to the zip file
            String zipFilePathFull = getServletContext().getRealPath("/") + "images/" + zipFileName;
            File zipFile = new File(zipFilePathFull);
            if (!zipFile.exists() || zipFile.length() < 1) {
                LOGGER.severe("Zip file does not exist or is empty.");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
                return;
            }

            // Setting up the response to download the zip file
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(zipFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
            response.setContentType("application/zip");

            try (FileInputStream fis = new FileInputStream(zipFile);
                 BufferedInputStream buff = new BufferedInputStream(fis);
                 OutputStream myout = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = buff.read(buffer)) > 0) {
                    myout.write(buffer, 0, bytesRead);
                }

                myout.flush();
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "Client aborted the connection", e);
                zipFile.delete(); // Delete incomplete file
                return;
            }

            // Delete the generated zip file after sending it
            zipFile.delete();

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error during file download process", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error. Download failed.");
        }
    }
}
